package services

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/topfreegames/pitaya"
	"pitaya_new_chatroom/manager/roomManager"
	"pitaya_new_chatroom/protos"
	"pitaya_new_chatroom/room"
	"pitaya_new_chatroom/utils"
	"sync"

	"github.com/topfreegames/pitaya/component"
)


type Backend struct{

	component.Base
	once sync.Once

}
type BackendRemote struct{

	component.Base
}



func (r *Backend) LeaveRoom(ctx context.Context,data *protos.LeaveRoomReq)(*protos.RequestRes,error){
	roomInfo,isExists := roomManager.RoomMgr.GetRoom(data.RoomId)

	if !isExists {
		return utils.Utils.ReturnTextData("enterRespond", "10001",ctx),nil
	}

	res,err:=roomInfo.LeaveRoom(ctx)

	return res,err
}


func (r *Backend) CreateRoom(ctx context.Context)(*protos.RequestRes,error){
	s := pitaya.GetSessionFromCtx(ctx)
	uid:= s.UID()

	if uid == ""{
		return utils.Utils.ReturnTextData("createRoomRespond","1001" ,ctx),nil
	}
	l := pitaya.GetDefaultLoggerFromCtx(ctx)

	room:= room.NewRoom()

	// 需要给这个房间创建一个组
	err:= pitaya.GroupCreate(context.Background(),room.ID)
	if err !=nil{
		l.Error(err.Error())

		return utils.Utils.ReturnTextData("createRoomRespond","1000" ,ctx),nil
	}

	roomManager.RoomMgr.AddRoom(room.ID,room)

	res :=utils.Utils.ReturnComplexData("createRoomRespond",200 ,room)

	return res,nil
}


func (r *Backend) Enter(ctx context.Context,data *protos.EnterRoomReq) (*protos.RequestRes,error){

	fmt.Println("Enter",data.RoomId)
	roomInfo,isExists := roomManager.RoomMgr.GetRoom(data.RoomId)
	fmt.Println("请求的房间信息",roomInfo,isExists)
	if !isExists {
		return utils.Utils.ReturnTextData("enterRespond","10001",ctx),nil
	}

	res,err := roomInfo.Enter(ctx,data)

	if err !=nil{
		fmt.Printf("err%s",err.Error())
		return utils.Utils.ReturnTextData("enterRespond","10002",ctx),err
	}

	return res,nil

}

func (r *Backend) Message(ctx context.Context, data *protos.SendMessageToRoomReq)(*protos.RequestRes,error){

	roomInfo,isExists := roomManager.RoomMgr.GetRoom(data.RoomId)

	if !isExists {
		return utils.Utils.ReturnTextData("enterRespond","10001",ctx),nil
	}

	res,err:=roomInfo.Message(ctx,data)

	return res,err
}

func(r *Backend) CleanRoom(ctx context.Context,data *protos.CleanRoomReq)(*protos.RequestRes,error){
	roomInfo,isExists := roomManager.RoomMgr.GetRoom(data.RoomId)

	if !isExists {
		return utils.Utils.ReturnTextData("enterRespond", "10001",ctx),nil
	}


	res,err:= roomInfo.CleanRoom(ctx,data)


	return res,err
}


// 接受一下前端 session断开rpc通知

func (r *Backend) UserSessionClose(ctx context.Context , data *protos.RPCReq)(*protos.RPCRes,error){

	reqData:= make(map[string]interface{})
	json.Unmarshal([]byte(data.Msg),&reqData)
	roomId := reqData["roomId"].(string)
	ret:= &protos.RPCRes{}
	uid:= reqData["uid"].(string)
	roomInfo,isExists := roomManager.RoomMgr.GetRoom(roomId)
	fmt.Printf("rpc request reqData:%v, roomInfo:%v, uid:%v",reqData,roomInfo,uid)

	if !isExists {
		ret.Code = 10001
		ret.Msg = "房间不存在"
		return ret, nil
	}

	if roomId == "" ||uid == "" {
		ret.Code = 11000
		ret.Msg = "当前用户不在房间中"
		return ret, nil
	}

	userInfo,err := roomInfo.ClearUserInfo(uid)


	if err !=nil{
		ret.Code = 11001
		ret.Msg = err.Error()
	}else{
		buf,_:= json.Marshal(userInfo)
		ret.Code = 200
		ret.Msg = string(buf)
	}


	return ret, nil
}

func(r *Backend)BeforeShutdown(){
	// 保证只执行一次  进程关闭了后 删除该进程使用的组信息
	r.once.Do(func(){
		rooms:=roomManager.RoomMgr.GetRoomAll()
		rooms.Range(func(id ,room interface{})bool{
			pitaya.GroupDelete(context.Background(),id.(string))
			return true
		})
	})


}